//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
//来电记录
class CallHistoryModel : BaseViewModel {
    @Published var items = [CallHistoryBean]()
    @Published var status = ""
    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            let list = try await BackupsManager.shared.getDelegateDiary()?.queryActiveCall(
                userId: userManager.getUserId(),
                pageNo: self.pageNo,
                pageSize: self.pageSize
            ) ?? []
            for bean in list {
                bean.aiRole = try await DiaryExt.getRole(bean)
            }
            try check(!isRefresh || !list.isEmpty, "暂无来电记录")
            return list
        } suc: { diarys in
            self.status = ""
            diarys[0].voiceHex = ""
            showLog(toJson(diarys[0]))
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func doDel(index: Int, bean: CallHistoryBean,sucResult: @escaping ()-> Void) {
        request {
            try await BackupsManager.shared.getDelegateDiary()?.deleteActiveCall(bean: bean)
        } suc: { _ in
            sucResult()
        } fail: {
            showToast($0.message)
        }
    }
    
    func doVoice(bean: CallHistoryBean, isWait:Bool = false) {
        if (bean.content ?? "").isEmpty {
            return
        }
        request {
            try check(userManager.isVip() || AiChatExt.isAiEnabled(3)) {
                "AI 功能已用尽,请前往活动领取次数"
            }
            //旧数据
            if (bean.aiRole == nil) {
                //则获取当前的角色
                bean.aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: nil)
            }
            let voiceBean = bean.aiRole?.voice
            let (hexString, hexData) = try await AiChatExt.doAiVoiceTest(text: bean.content, voiceId: voiceBean?.voiceId, voiceHex: bean.voiceHex)
            if ((bean.voiceHex ?? "").isEmpty && (bean.content?.count ?? 0) < 130) {
                //保存起来，下次就不需要了
                bean.voiceHex = hexString
                try await BackupsManager.shared.getDelegateDiary()?.updateActiveCall(bean: bean)
            }
            return (bean.aiRole ?? AiRoleBean(), hexData)
        } suc: { (aiRole , hexData) in
            //唤起语音播放界面
            let callParam : VoiceCallParam = VoiceCallParam()
            callParam.hexData = hexData
            callParam.isStart = false
            callParam.logo = aiRole.avatar
            callParam.showName = aiRole.name
            if isWait {
                commonManager.showVoiceWaitDialog(callParam)
            } else {
                commonManager.showVoiceCall(callParam)
            }
        } fail: {
            showToast($0.message)
        }
        
    }
}
